package tech.lq0.dreamaticvoyage.network;

import net.minecraft.client.Minecraft;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;
import tech.lq0.dreamaticvoyage.block.entity.FukamizuFermenterBlockEntity;
import tech.lq0.dreamaticvoyage.gui.menu.BaseEnergyMenu;
import tech.lq0.dreamaticvoyage.gui.menu.PhantasmalVoyagerMenu;
import tech.lq0.dreamaticvoyage.network.packet.ContainerComponentDataSyncPacket;
import tech.lq0.dreamaticvoyage.network.packet.ContainerDataSyncPacket;
import tech.lq0.dreamaticvoyage.network.packet.FukamizuFermenterSyncPacket;

import java.util.List;
import java.util.function.Supplier;

public class ClientPacketHandler {

    public static void handleContainerDataSyncPacket(int containerId, List<ContainerDataSyncPacket.Pair> data, Supplier<NetworkEvent.Context> ctx) {
        if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
            Minecraft mc = Minecraft.getInstance();
            if (mc.player != null && mc.player.containerMenu.containerId == containerId) {
                data.forEach(p -> ((BaseEnergyMenu) mc.player.containerMenu).setData(p.id, p.data));
            }
        }
    }

    public static void handleFukamizuFermenterSyncPacket(FukamizuFermenterSyncPacket message, Supplier<NetworkEvent.Context> ctx) {
        if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
            var player = Minecraft.getInstance().player;
            if (player == null) return;
            var level = player.level();
            BlockEntity be = level.getBlockEntity(message.pos());
            if (be instanceof FukamizuFermenterBlockEntity blockEntity) {
                blockEntity.clientInputFluid = message.inputStack();
                blockEntity.clientOutputFluid = message.outputStack();
            }
        }
    }

    public static void handleContainerComponentDataSyncPacket(int containerId, List<ContainerComponentDataSyncPacket.Pair> data, Supplier<NetworkEvent.Context> ctx) {
        if (ctx.get().getDirection().getReceptionSide() == LogicalSide.CLIENT) {
            Minecraft mc = Minecraft.getInstance();
            if (mc.player != null && mc.player.containerMenu.containerId == containerId) {
                data.forEach(p -> ((PhantasmalVoyagerMenu) mc.player.containerMenu).setData(p.id, p.data));
            }
        }
    }
}
